/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import domain.Insuranceconsumption;
import domain.Insurancecontract;
import domain.Invoice;
import domain.Userdom;
import java.sql.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;



/**
 *
 * @author Alejandro
 */
public class InsuranceconsumptionDao {
    EntityManager em;
    EntityTransaction tx;

    public InsuranceconsumptionDao() {
        em = SingletonDao.getInstance().getEntityManager();
        tx = SingletonDao.getTx();
    }

    public Insuranceconsumption getInsuranceconsumption(Integer idI){
        Insuranceconsumption i = (Insuranceconsumption) em.createNativeQuery("select * from insuranceconsumption as i where i.idInsuranceCons='"+idI+"'", Insuranceconsumption.class).getSingleResult();
        return i;
    }

    public void saveInsuranceconsumption(Insuranceconsumption i){
        tx.begin();
        em.persist(i);
        tx.commit();
    }

    public void removeInsuranceconsumption (Insuranceconsumption i){
        tx.begin();
        em.remove(i);
        tx.commit();
    }

    public Insuranceconsumption getInsuranceconsumptionDate(Insurancecontract m){
        Insuranceconsumption ec = null;
        Date date = new Date(new java.util.Date().getTime());
        int month = date.getMonth();
        int year = date.getYear()+1900;
        int day = date.getDate();
        List list = em.createNativeQuery("select * from insuranceconsumption as e, contract as cont, consumption as cons where cont.idContract='"+m.getContract().getIdContract()+"' and  e.consFK=cons.idCons and cons.consFk=cont.idContract and e.dateTo>'"+year+"-"+month+"-"+day+"'", Insuranceconsumption.class).getResultList();
        if(!list.isEmpty()){
            ec = (Insuranceconsumption) list.get(0);
        }
        return ec;
    }

    public List<Insuranceconsumption> getInsuranceListConsumption(Invoice i){
        List<Insuranceconsumption> l = em.createNativeQuery("select * from insuranceconsumption as ic where ic.invoiceFK ='"+i.getIdInvoice()+"'", Insuranceconsumption.class).getResultList();
        return l;
    }


}
